import React, { useEffect, useLayoutEffect, useState, useRef } from 'react';
import { history } from 'umi'
import { Table, Tooltip, Button, Popover, Form, Input, Modal, Icon, Checkbox, Tag, message } from 'antd';
import Employee from '@/pages/Organization/OrgFlow/components/employee';
import cn from 'classnames';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import authHelper from '@/utils/auth/helper';
import { eventTrack } from '@/utils/track';
// import { guid } from '@/utils/utils';
// import { GuideByServerFlag } from '@/components';
// import supervisorSetGuide from '@/assets/employeeManage/supervisorSetGuide@2x.jpeg';
import { flattenTree } from '@/utils/tree';
import AuthComponent from '@/utils/auth/AuthComponent';
import { isSupervisorApprovaling } from '@/pages/Organization/OrgFlow/utils';
import { getOrgList, orgDeleteCheck, batchSaveOrganizationChange } from '../../services';
import styles from './index.less';

const { checkCode } = authHelper;

// 固定参数
const fixedParams = {
    countEmployeeNumFlag: 1,
    getEmployeeFlag: 1,
    showNumberFlag: 1
};

const organizationTypeDict = ['', '集团', '公司', '部门'];

// 数组里得数字字符串转纯数字
const getNumber = arr => arr.map(item => Number(item));

// 暂时隐藏引导，等替换后删除该注释
// eslint-disable-next-line @typescript-eslint/no-unused-vars
// const GuideStep = ({ record, dataSource, children }) => {
//     const isFirstShowGuideItem = findValueInTree(dataSource, 'organizationType', 3);
//     if (record.organizationPath === isFirstShowGuideItem.organizationPath) {
//         return (
//             <GuideByServerFlag.Step
//                 index={3}
//                 title="主管设置和修改"
//                 content={
//                     <div>
//                         <img
//                             alt=""
//                             src={supervisorSetGuide}
//                             width="416"
//                             style={{ border: 'dashed 1px #ddd', marginTop: 10, marginBottom: 10 }}
//                         />
//                         <p>
//                             鼠标悬停<strong>主管信息位置</strong>可直接进行<strong>设置主管</strong>和
//                             <strong>修改</strong>
//                         </p>
//                     </div>
//                 }
//                 placement="leftBottom"
//                 placeholderStyle={{ display: 'flex' }}
//             >
//                 {children}
//             </GuideByServerFlag.Step>
//         );
//     }
//     return children;
// };
const modText = text => {
    if (text) {
        return `(${text})`;
    }
    return '';
};

const modEmployeeName = text => {
    if (text.length > 50) {
        return `${text.substring(0, 49)}...`;
    }
    return text;
};

// 过滤数据
const filterTree = tree =>
    tree.map(({ children, ...props }) => {
        if (children && children.length > 0) {
            return { children: filterTree(children), ...props };
        }
        return { children: '', ...props };
    });

const OrgListTable = ({ form, location }) => {
    const { getFieldDecorator, getFieldsValue } = form;
    const { query: urlQuery } = location;
    const [loading, setLoading] = React.useState(false);
    const [dataSource, setDataSource] = React.useState([]);
    // const [filterValue, setFilterValue] = React.useState([]);
    const [expandAllRows, setExpandAllRows] = React.useState([]);

    const isComponentDestroyRef = useRef(false);

    // 判断是否存在请求参数
    const isEmptyObject = () => {
        let type = false;
        const arr = Object.keys(urlQuery);
        // 这里判断如果url上得数据存在值，则不为树结构
        arr.forEach(item => {
            if (
                urlQuery[item] !== '' &&
                urlQuery[item] !== undefined &&
                (Array.isArray(urlQuery[item]) ? urlQuery[item].length !== 0 : null)
            ) {
                type = true;
            }
        });

        return type ? 0 : 1;
    };
    const [query, setQuery] = useState({
        employeeNameLike: urlQuery.employeeNameLike || '',
        organizationNameLike: urlQuery.organizationNameLike || '',
        organizationCode: ''
        // organizationCode: ''
    });

    // 更新url及query
    const routerReplace = newQuery => {
        history.push({
            query: {
                ...urlQuery,
                ...newQuery
            }
        });
        setQuery({
            ...query,
            ...newQuery
        });
    };

    // 请求参数的加工处理
    const getParams = () => {
        const param = getFieldsValue();
        const { organizationNameLike, employeeNameLike, ...rest } = param;
        // 这里处理了如果没值，字段为undefined
        return {
            ...rest,
            organizationNameLike: organizationNameLike !== '' ? organizationNameLike : undefined,
            employeeNameLike: employeeNameLike !== '' ? employeeNameLike : undefined
        };
    };

    // 批量删除节点
    const handleDelete = async record => {
        const { organizationType, organizationCode } = record;
        await eventTrack({
            eventName: 'personnel_management_organization_orgflow_list_operator_click',
            pageName: 'personnel_management_organization',
            eventProps: {
                click_context: `${record.organizationName}-删除`
            }
        });
        const confirmModal = Modal.confirm({
            title: '确定删除？',
            icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
            okText: '确认',
            cancelText: '取消',
            okButtonProps: {
                disabled: organizationType === 3
            },
            content: (
                <>
                    {organizationType === 3 ? (
                        <div className={styles.deleteInfo}>
                            <p>删除此机构前请先确认：</p>
                            <p>· 此机构下是否有在职员工？</p>
                            <p>· 此机构下是否有岗位正在招聘？</p>
                            <p>· 此机构下是否有正在入职的员工？</p>
                            <p>上述情况皆无，才能够删除此机构</p>
                            <div>
                                <Checkbox
                                    onChange={e => {
                                        confirmModal.update({
                                            okButtonProps: {
                                                disabled: !e.target.checked
                                            }
                                        });
                                    }}
                                >
                                    确认删除此机构
                                </Checkbox>
                            </div>
                        </div>
                    ) : (
                        `删除${organizationTypeDict[organizationType]}将无法恢复，确定删除吗？`
                    )}
                </>
            ),
            onOk: async () => {
                setLoading(true);
                // 删除前校验
                const { msg, code: delCheckCode } = await orgDeleteCheck({
                    organizationCode
                });
                if (delCheckCode === 10000) {
                    // 流程不存在提示
                    const { workFlowPathname, workFlowQuery, workFlowErrorMsg } = await hasWorkFlowByType(
                        'organizationApply',
                        false
                    );
                    if (!workFlowPathname) {
                        Modal.error({
                            title: '删除失败',
                            icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
                            content: workFlowErrorMsg,
                            okText: '我知道了'
                        });
                        return;
                    }
                    // 扁平化record, 并删除掉 children 字段
                    const deleteData = flattenTree(record).map(item => {
                        const { children, ...result } = item;
                        return { ...result, organizationType }; // 列表删除要将操作类型变成单条删除
                    });
                    // 分组放置要提交的数据
                    const groupSubmitData = {
                        delete: deleteData
                    };
                    // 提交更新
                    const { code, msg: errormsg, data: id } = await batchSaveOrganizationChange(groupSubmitData);
                    // 跳转到流程
                    if (code === 10000) {
                        history.push({
                            pathname: workFlowPathname,
                            query: { ...workFlowQuery, hiDataId: id },
                            state: { tabRoute: true, tabRefresh: true }
                        });
                    } else {
                        message.error(errormsg);
                    }
                } else {
                    Modal.error({
                        title: '删除失败',
                        icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
                        content: msg,
                        okText: '我知道了'
                    });
                }
                setLoading(false);
            }
        });
    };

    // 查询
    const handleSubmit = e => {
        e.preventDefault();
        routerReplace({
            ...getParams()
        });
        // 埋点
        eventTrack({
            eventName: 'personnel_management_organization_orgflow_list_search_submit_click',
            pageName: 'personnel_management_organization',
            eventProps: {
                submit_context: `层级:${query.organizationNameLike || '空'},主管:${query.employeeNameLike || '空'}`
            }
        });
    };

    const renderHref1 = (text, record) =>
        record.organizationType === 3 ? (
            <span>-</span>
        ) : (
            <a
                onClick={async () => {
                    await eventTrack({
                        eventName: 'personnel_management_organization_orgflow_list_company_num_click',
                        pageName: 'personnel_management_organization',
                        eventProps: {
                            click_context: `${record.organizationName}-${record.companyNumber}`
                        }
                    });

                    history.push({
                        pathname: '/office/personnelManagement/organization/companyManage',
                        query: {
                            organizationPermissions: record.organizationPermissions,
                            organizationType: 2,
                            organizationPath: record.organizationPath,
                            organizationName: record.organizationName,
                            organizationCode: record.organizationCode,
                            auditStatus: record.auditStatus,
                            num: Number(text)
                        }
                    });
                }}
            >
                {text}
            </a>
        );
    const getOperation = (text, record) => {
        const isSuperApprovaling = isSupervisorApprovaling(record);

        return (
            <React.Fragment>
                <div className={styles.tableAction}>
                    {checkCode('office:orgs:organization:new') && (
                        <>
                            <Tooltip title="新增公司">
                                <i
                                    disabled={record.organizationType === 3 || record.auditStatus !== 2}
                                    className={cn('iconfont iconlistfunction_addcompany_icon_default', styles.icon)}
                                    onClick={async () => {
                                        await eventTrack({
                                            eventName: 'personnel_management_organization_orgflow_list_operator_click',
                                            pageName: 'personnel_management_organization',
                                            eventProps: {
                                                click_context: `${record.organizationName}-新增公司`
                                            }
                                        });

                                        history.push({
                                            pathname: '/office/personnelManagement/organization/companyadd',
                                            query: {
                                                organizationCode: record.organizationCode,
                                                organizationPath: record.organizationPath,
                                                organizationName: record.organizationName
                                            }
                                        });
                                    }}
                                />
                            </Tooltip>
                            <Tooltip title="新增部门">
                                <i
                                    disabled={record.organizationType === 2 || record.auditStatus !== 2}
                                    className={cn('iconfont iconlistfunction_adddepartment_icon_default', styles.icon)}
                                    onClick={async () => {
                                        await eventTrack({
                                            eventName: 'personnel_management_organization_orgflow_list_operator_click',
                                            pageName: 'personnel_management_organization',
                                            eventProps: {
                                                click_context: `${record.organizationName}-新增部门`
                                            }
                                        });
                                        // 这里处理了是否展示部门编辑的时候顶部那一条提示
                                        // 如果children为空，显示 如果childer不为空并且其中一个部门审核通过则不显示.
                                        // 如果下级部门都在审批中，一个或者多个，没有审批通过的，则显示
                                        const getShowTips = () => {
                                            if (record?.children === '') {
                                                return true;
                                            }
                                            if (record?.children.length > 0) {
                                                if (record?.children?.some(item => item.auditStatus === 2)) {
                                                    return false;
                                                }
                                                if (record?.children?.some(item => item.auditStatus === 1)) {
                                                    return true;
                                                }
                                            }
                                            return false;
                                        };
                                        history.push({
                                            pathname: '/office/personnelManagement/organization/departmentadd',
                                            query: {
                                                organizationCode: record.organizationCode,
                                                organizationPath: record.organizationPath,
                                                organizationName: record.organizationName,
                                                showTips: getShowTips()
                                            }
                                        });
                                    }}
                                />
                            </Tooltip>
                        </>
                    )}

                    {checkCode('office:orgs:organization:duty:new') && (
                        <Tooltip title="新增岗位">
                            <i
                                disabled={
                                    record.organizationType === 1 ||
                                    record.organizationType === 2 ||
                                    record.auditStatus !== 2
                                }
                                className={cn('iconfont iconlistfunction_addpost_icon_default', styles.icon)}
                                onClick={async () => {
                                    await eventTrack({
                                        eventName: 'personnel_management_organization_orgflow_list_operator_click',
                                        pageName: 'personnel_management_organization',
                                        eventProps: {
                                            click_context: `${record.organizationName}-新增岗位`
                                        }
                                    });
                                    history.push({
                                        pathname: '/office/personnelManagement/organization/postadd',
                                        query: {
                                            organizationCode: record.organizationCode,
                                            organizationPath: record.organizationPath,
                                            organizationName: record.organizationName
                                        }
                                    });
                                }}
                            />
                        </Tooltip>
                    )}

                    {checkCode('office:orgs:organization:edit') && (
                        <Tooltip title="编辑">
                            <i
                                disabled={record.auditStatus !== 2 || isSuperApprovaling}
                                className={cn('iconfont iconlistfunction_edit_icon_default', styles.icon)}
                                onClick={async () => {
                                    await eventTrack({
                                        eventName: 'personnel_management_organization_orgflow_list_operator_click',
                                        pageName: 'personnel_management_organization',
                                        eventProps: {
                                            click_context: `${record.organizationName}-编辑`
                                        }
                                    });
                                    if (record.organizationType === 3) {
                                        history.push({
                                            pathname: '/office/personnelManagement/organization/departmentedit',
                                            query: {
                                                organizationCode: record.organizationCode,
                                                organizationPath: record.organizationPath,
                                                organizationName: record.organizationName
                                            }
                                        });
                                    } else {
                                        history.push({
                                            pathname: '/office/personnelManagement/organization/companyedit',
                                            query: {
                                                organizationCode: record.organizationCode,
                                                organizationPath: record.organizationPath,
                                                organizationName: record.organizationName
                                            }
                                        });
                                    }
                                }}
                            />
                        </Tooltip>
                    )}

                    {checkCode('office:orgs:organization:delete') && (
                        <Tooltip title="删除">
                            <i
                                disabled={
                                    record.auditStatus !== 2 || record.organizationType === 1 || isSuperApprovaling
                                }
                                className={cn(
                                    'iconfont iconlistfunction_delete_icon_default',
                                    styles.icon,
                                    styles.delect
                                )}
                                onClick={() => handleDelete(record)}
                            />
                        </Tooltip>
                    )}
                </div>
            </React.Fragment>
        );
    };
    const renderEllipsis = text => (
        <div style={{ width: '100%', minWidth: 300, position: 'relative' }}>
            <span
                style={{
                    position: 'absolute',
                    left: 0,
                    right: 0,
                    top: 0,
                    transform: 'translateY(-50%)',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis'
                }}
                title={text}
            >
                {text}
            </span>
        </div>
    );
    // 埋点用-过滤器的时候，获取选中的内容
    const getEventTrackCont = obj => {
        const { auditStatus, organizationType } = obj;
        const dict1 = [
            { text: '审批通过', value: 2 },
            { text: '审批中', value: 1 }
        ];
        const dict2 = [
            { text: '集团', value: 1 },
            { text: '公司', value: 2 },
            { text: '部门', value: 3 }
        ];
        const getValue = (keys, dict) => {
            if (Array.isArray(keys)) {
                return keys.map(v => dict.find(e => e.value === Number(v)).text).join();
            }
            return '';
        };

        eventTrack({
            eventName: 'personnel_management_organization_orgflow_list_status_screen_click',
            pageName: 'personnel_management_organization',
            eventProps: {
                click_context: `状态-${getValue(auditStatus, dict1)},类型-${getValue(organizationType, dict2)}`
            }
        });
    };
    // 表格渲染
    const columns = [
        {
            title: '层级',
            dataIndex: 'organizationName',
            width: 400,
            className: styles.organizationName,
            render: (text, record) => (
                <a
                    className={styles.title}
                    onClick={async e => {
                        e.stopPropagation();

                        // 埋点
                        await eventTrack({
                            eventName: 'personnel_management_organization_orgflow_list_level_orginfo_click',
                            pageName: 'personnel_management_organization',
                            eventProps: {
                                submit_context: record.organizationName
                            }
                        });

                        history.push({
                            pathname: `/office/personnelManagement/organization/${
                                record.organizationType === 3 ? 'departmentinfo' : 'companyinfo'
                            }`,
                            query: {
                                organizationCode: record.organizationCode,
                                organizationPath: record.organizationPath,
                                organizationName: record.organizationName
                            }
                        });
                    }}
                >
                    {renderEllipsis(text)}
                </a>
            )
        },
        {
            title: '状态',
            dataIndex: 'auditStatus',
            filteredValue:
                (urlQuery.auditStatus &&
                    (Array.isArray(urlQuery.auditStatus)
                        ? getNumber(urlQuery.auditStatus)
                        : getNumber([urlQuery.auditStatus]))) ||
                '',
            filterMultiple: true,

            filters: [
                { text: '审批通过', value: 2 },
                { text: '审批中', value: 1 }
            ],
            render: text => {
                const auditStatus = ['未审批', '审批中', '审批通过', '审批驳回'];
                return <span style={Number(text) === 1 ? { color: '#FFA22D' } : {}}>{auditStatus[text]}</span>;
            }
        },
        {
            title: '类型',
            dataIndex: 'organizationType',
            filteredValue:
                (urlQuery.organizationType &&
                    (Array.isArray(urlQuery.organizationType)
                        ? getNumber(urlQuery.organizationType)
                        : getNumber([urlQuery.organizationType]))) ||
                '',
            filterMultiple: true,
            filters: [
                { text: '集团', value: 1 },
                { text: '公司', value: 2 },
                { text: '部门', value: 3 }
            ],
            render: type => {
                const orgType = { 1: '集团', 2: '公司', 3: '部门' };
                return <span>{orgType[type]}</span>;
            }
        },
        {
            title: '公司',
            dataIndex: 'companyNumber',
            render: (text, record) => renderHref1(text, record)
        },
        {
            title: (
                <div>
                    部门<span>(直属/下属)</span>
                </div>
            ),
            dataIndex: 'departmentCounts',
            render: (text, record) => {
                const { directDepartmentNum = 0, underDepartmentNumber = 0 } = record;
                return record.organizationType === 2 ? (
                    <span>- / -</span>
                ) : (
                    <span>
                        <a
                            onClick={async () => {
                                await eventTrack({
                                    eventName:
                                        'personnel_management_organization_orgflow_list_dept_directly_under_num_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-直属部门数量-${record.directDepartmentNum}`
                                    }
                                });

                                history.push({
                                    pathname: '/office/personnelManagement/organization/departmentManage',
                                    query: {
                                        organizationPermissions: record.organizationPermissions,
                                        organizationPath: record.organizationPath,
                                        organizationType: 3,
                                        organizationCode: record.organizationCode,
                                        organizationName: record.organizationName,
                                        auditStatus: record.auditStatus,
                                        num: directDepartmentNum
                                    }
                                });
                            }}
                        >
                            {directDepartmentNum}
                        </a>
                        &nbsp;/&nbsp;
                        <a
                            onClick={async () => {
                                await eventTrack({
                                    eventName: 'personnel_management_organization_orgflow_list_dept_sub_num_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-下属部门数量-${record.underDepartmentNumber}`
                                    }
                                });

                                history.push({
                                    pathname: '/office/personnelManagement/organization/subordinateManage',
                                    query: {
                                        organizationPermissions: record.organizationPermissions,
                                        organizationPath: record.organizationPath,
                                        organizationCode: record.organizationCode,
                                        organizationName: record.organizationName,
                                        auditStatus: record.auditStatus,
                                        organizationType: 3,
                                        num: underDepartmentNumber
                                    }
                                });
                            }}
                        >
                            {underDepartmentNumber}
                        </a>
                    </span>
                );
            }
        },
        {
            title: (
                <div>
                    岗位<span>(编制/在职)</span>
                </div>
            ),
            dataIndex: 'employeeNum',
            render: (text, record) => {
                const { employeeNum = 0, planNum = 0 } = record;
                return record.organizationType === 2 ? (
                    <span>- / -</span>
                ) : (
                    <span>
                        <a
                            onClick={async () => {
                                await eventTrack({
                                    eventName:
                                        'personnel_management_organization_department_manage_post_establishment_num_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-岗位编制人数-${record.planNum}`
                                    }
                                });

                                history.push({
                                    pathname: '/office/personnelManagement/organization/postList',
                                    query: {
                                        organizationPermissions: record.organizationPermissions,
                                        organizationPath: record.organizationPath,
                                        organizationCode: record.organizationCode,
                                        organizationName: record.organizationName,
                                        auditStatus: record.auditStatus,
                                        num: planNum
                                    }
                                });
                            }}
                        >
                            {planNum}
                        </a>
                        &nbsp;/&nbsp;
                        <a
                            onClick={async () => {
                                await eventTrack({
                                    eventName:
                                        'personnel_management_organization_department_manage_post_incumbency_num_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${record.organizationName}-岗位在职人数-${record.employeeNum}`
                                    }
                                });

                                history.push({
                                    pathname: '/office/personnelManagement/organization/employeeList',
                                    query: {
                                        organizationCodes: record.organizationCode || ''
                                    }
                                });
                            }}
                        >
                            {employeeNum}
                        </a>
                    </span>
                );
            }
        },
        {
            title: '主管',
            dataIndex: 'orgLeaders',
            // width: 120,
            render: (text, record) => {
                const {
                    orgLeaders,
                    organizationCode,
                    organizationType,
                    organizationPermissions,
                    leaderDutyAlias,
                    leaderDutyAuditStatus
                } = record;
                const renderCell = () => {
                    if (orgLeaders.length > 0) {
                        return orgLeaders.map(employee => {
                            const {
                                employeeName,
                                dutyType
                                // , titleName
                            } = employee;
                            // const keyId = guid();
                            // 该员工是主管岗位的时候不能修改
                            const hasSupervisorEdit =
                                employee.showStatus < 0 ||
                                record.auditStatus === 1 ||
                                organizationPermissions === 0 ||
                                dutyType === 1 ||
                                leaderDutyAuditStatus === 1;
                            return (
                                <>
                                    <Popover
                                        // key={keyId}
                                        getPopupContainer={node => node}
                                        content={
                                            <Employee
                                                employeeCode={employee.employeeCode}
                                                organizationCode={employee.organizationCode}
                                                organizationType={record.organizationType}
                                            />
                                        }
                                        onVisibleChange={async v => {
                                            if (v) {
                                                await eventTrack({
                                                    eventName:
                                                        'personnel_management_organization_orgflow_list_org_leader_click',
                                                    pageName: 'personnel_management_organization',
                                                    eventProps: {
                                                        click_context: `${record.organizationName}-${employeeName}`
                                                    }
                                                });
                                            }
                                        }}
                                        placement="bottomLeft"
                                    >
                                        <span style={{ marginRight: 4 }}>
                                            {modEmployeeName(employeeName)}
                                            {leaderDutyAuditStatus === 2 ? modText(leaderDutyAlias) : null}
                                            {dutyType === 0 ? (
                                                <Tag color="blue" style={{ marginLeft: 8 }}>
                                                    兼
                                                </Tag>
                                            ) : null}
                                            {/* {modText(titleName)} */}
                                        </span>
                                    </Popover>

                                    {hasSupervisorEdit ? null : (
                                        <AuthComponent code="office:orgs:organization:list:editLeader">
                                            <a
                                                className={cn(styles.setText, 'setText')}
                                                onClick={() => {
                                                    history.push({
                                                        pathname:
                                                            '/office/personnelManagement/organization/orgflow/supervisorEdit',
                                                        query: {
                                                            organizationCode,
                                                            entranceSign: 'org'
                                                        }
                                                    });
                                                }}
                                            >
                                                修改
                                            </a>
                                        </AuthComponent>
                                    )}
                                    {employee.showStatus === -1001 ? (
                                        <Tooltip placement="top" title="主管设置审批中">
                                            <Tag
                                                style={{ cursor: 'pointer' }}
                                                color="orange"
                                                onClick={() => {
                                                    history.push({
                                                        pathname: '/personal/portal/myAuditRead/myAuditReadDetail',
                                                        query: {
                                                            applicationNo: employee?.leaderApplicationNo
                                                        }
                                                    });
                                                }}
                                            >
                                                审批中
                                            </Tag>
                                        </Tooltip>
                                    ) : null}
                                    {employee.showStatus === -1002 ? (
                                        <Tooltip placement="top" title="主管修改审批中">
                                            <Tag
                                                style={{ cursor: 'pointer' }}
                                                color="orange"
                                                onClick={() => {
                                                    history.push({
                                                        pathname: '/personal/portal/myAuditRead/myAuditReadDetail',
                                                        query: {
                                                            applicationNo: employee?.leaderApplicationNo
                                                        }
                                                    });
                                                }}
                                            >
                                                审批中
                                            </Tag>
                                        </Tooltip>
                                    ) : null}
                                    {employee.showStatus === -1003 ? (
                                        <Tooltip placement="top" title="主管卸任审批中">
                                            <Tag
                                                style={{ cursor: 'pointer' }}
                                                color="orange"
                                                onClick={() => {
                                                    history.push({
                                                        pathname: '/personal/portal/myAuditRead/myAuditReadDetail',
                                                        query: {
                                                            applicationNo: employee?.leaderApplicationNo
                                                        }
                                                    });
                                                }}
                                            >
                                                审批中
                                            </Tag>
                                        </Tooltip>
                                    ) : null}
                                </>
                            );
                        });
                    }

                    if (
                        leaderDutyAlias &&
                        orgLeaders.length === 0 &&
                        organizationType === 3 &&
                        organizationPermissions === 1
                    ) {
                        return (
                            <>
                                <span style={{ marginRight: 4 }}>-</span>
                                {leaderDutyAuditStatus === 2 ? modText(leaderDutyAlias) : null}
                                {record.auditStatus !== 1 && leaderDutyAuditStatus !== 1 && (
                                    <AuthComponent code="office:orgs:organization:list:setLeader">
                                        <a
                                            className={cn(styles.setText, 'setText')}
                                            onClick={() => {
                                                history.push({
                                                    pathname:
                                                        '/office/personnelManagement/organization/orgflow/supervisorSet',
                                                    query: {
                                                        organizationCode,
                                                        entranceSign: 'org'
                                                    }
                                                });
                                            }}
                                        >
                                            设置
                                        </a>
                                    </AuthComponent>
                                )}
                            </>
                        );
                    }
                    return '-';
                };
                return (
                    <div className="setOrgLeaders">
                        {/* <GuideStep record={record} dataSource={dataSource}> */}
                        {/*    {renderCell()} */}
                        {/* </GuideStep> */}
                        {renderCell()}
                    </div>
                );
            }
        },
        {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            width: 250,
            render: (text, record) => (record.organizationPermissions ? getOperation(text, record) : null)
        }
    ];

    // 请求数据
    const fetchList = async () => {
        setLoading(true);
        const res = await getOrgList(
            { ...query, showTreeFlag: isEmptyObject(), auditStatus: '', organizationType: '' },
            fixedParams
        );
        if (res.code === 10000) {
            if (Array.isArray(res.data)) {
                setDataSource(res.data);
            } else {
                setDataSource([]);
            }
        }

        setLoading(false);
    };
    // 表格变化
    const handleTableChange = React.useCallback(async (pagination, filters) => {
        if (filters) {
            getEventTrackCont(filters);
            // setFilterValue(filters);
            routerReplace({
                ...getParams(),
                ...filters
            });
        }
    });

    // 通过过滤条件，前端过滤数据
    const processDataSource = React.useMemo(() => {
        const { auditStatus, organizationType } = urlQuery;
        if (
            (urlQuery !== '' && auditStatus && auditStatus.length > 0) ||
            (urlQuery !== '' && organizationType && organizationType.length > 0)
        ) {
            let arr = [];
            if (auditStatus && auditStatus.length > 0) {
                arr = dataSource.filter(item => getNumber(auditStatus).includes(item.auditStatus));
            }
            if (organizationType && organizationType.length > 0) {
                arr = dataSource.filter(item => getNumber(organizationType).includes(item.organizationType));
            }
            if (auditStatus && auditStatus.length > 0 && organizationType && organizationType.length > 0) {
                arr = dataSource.filter(
                    item =>
                        getNumber(auditStatus).includes(item.auditStatus) &&
                        getNumber(organizationType).includes(item.organizationType)
                );
            }
            return arr;
        }

        return dataSource;
    }, [urlQuery, dataSource]);

    React.useEffect(() => {
        const { employeeNameLike, organizationNameLike } = urlQuery;

        form.setFieldsValue({
            employeeNameLike,
            organizationNameLike
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(() => {
        fetchList();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [urlQuery]);

    useEffect(
        () => () => {
            isComponentDestroyRef.current = true;
        },
        []
    );

    const tableDataSource = React.useMemo(() => filterTree(processDataSource), [processDataSource]);

    useLayoutEffect(() => {
        // 需要展开两层节点
        if (Array.isArray(tableDataSource)) {
            const rows = [];
            if (tableDataSource[0]) {
                rows.push(tableDataSource[0].organizationCode);
                const level2nodes = tableDataSource[0].children
                    ? tableDataSource[0].children.filter(item => item.children.length)
                    : [];
                if (level2nodes) {
                    level2nodes.forEach(item => {
                        rows.push(item.organizationCode);
                    });
                }
            }
            const tempRowKeys = JSON.parse(sessionStorage.getItem('orgListTableExpandedRowKeys') || '[]');
            setExpandAllRows(tempRowKeys.length > 0 ? tempRowKeys : rows);
        }
    }, [tableDataSource, JSON.stringify(sessionStorage.getItem('orgListTableExpandedRowKeys'))]);

    return (
        <div>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Form layout="inline" onSubmit={handleSubmit} className={styles.formClass} style={{ marginBottom: 16 }}>
                    <Form.Item label="层级">
                        {getFieldDecorator('organizationNameLike')(
                            <Input
                                placeholder="请输入层级"
                                allowClear
                                onFocus={() => {
                                    eventTrack({
                                        eventName: 'personnel_management_organization_orgflow_list_level_input_click',
                                        pageName: 'personnel_management_organization'
                                    });
                                }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="主管">
                        {getFieldDecorator('employeeNameLike')(
                            <Input
                                placeholder="请输入主管"
                                allowClear
                                onFocus={() => {
                                    eventTrack({
                                        eventName: 'personnel_management_organization_orgflow_list_leader_input_click',
                                        pageName: 'personnel_management_organization'
                                    });
                                }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            搜索
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            <Table
                className={styles.tableAui}
                loading={loading}
                expandedRowKeys={expandAllRows}
                onExpandedRowsChange={e => {
                    // console.log('isComponentDestroyRef.current', isComponentDestroyRef.current);
                    if (!isComponentDestroyRef.current) {
                        setExpandAllRows(e);
                        sessionStorage.setItem('orgListTableExpandedRowKeys', JSON.stringify(e));
                    }
                }}
                onExpand={(e, record) => {
                    // 埋点
                    eventTrack({
                        eventName: 'personnel_management_organization_orgflow_list_level_open_close_click',
                        pageName: 'personnel_management_organization',
                        eventProps: {
                            submit_context: record.organizationName
                        }
                    });
                }}
                scroll={{ x: 'max-content' }}
                columns={columns}
                dataSource={tableDataSource}
                // rowKey={(record, index) => `${record?.organizationCode}-${index}`}
                rowKey="organizationCode"
                pagination={false}
                onChange={handleTableChange}
            />
        </div>
    );
};

export default Form.create()(OrgListTable);
